﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using SheepStorage.Domain.DTO.InputDto;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Domain.Enum;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using static System.Formats.Asn1.AsnWriter;

namespace SheepStorage.Service.DataImp
{
    public class UserInfoService:IUserInfoService
    {
        private readonly IBaseRepository<UserInfo> UserInforepository; 
        private readonly IBaseRepository<Role> Rolerepository;
        private readonly IBaseRepository<Personnel> Personnelrepository;
        private readonly IMapper mapper;

        public UserInfoService(IBaseRepository<UserInfo> UserInforepository, IBaseRepository<Role> Rolerepository, IBaseRepository<Personnel> Personnelrepository, IMapper mapper)
        {
           this. UserInforepository = UserInforepository;
          this.  Rolerepository = Rolerepository;
          this.Personnelrepository = Personnelrepository;
          this.mapper =  mapper;
        }
        /// <summary>
        /// 查询所有用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<  List<UserInfo>> GetUserInfo(string ?userTrueName,string ?departmentId,int   staffState=0)
        {
          //  var usserInfo= UserInforepository.GetAll().Where(c=>c.IsDel==0).ToList();
            var usserInfo =   UserInforepository.GetAll().Where(c=>c.IsDel==0).ToList();


            if (!string.IsNullOrEmpty(userTrueName))
            {
                 usserInfo = usserInfo.Where(c => c.UserTrueName.Contains(userTrueName)).ToList();
            }
            if(!string.IsNullOrEmpty(departmentId))
            {
                usserInfo = usserInfo.Where(c => c.DepartmentId.Contains(departmentId)).ToList();
            }
            if (staffState != 0)
            {
                usserInfo = usserInfo.Where(c => c.StaffState == staffState).ToList();
            }

            return   usserInfo;


        }
      
        
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
         public async Task< int> AddUserInfo(UserInfo info)
        {

            using (var scope = new TransactionScope())
            {
                try
                {
                   
                    info.UserCode=DateTime.Now.ToString("yyyyMMdd")+info.UserId.ToString();
                    info.UserNikeName = "友农_" + DateTime.Now.ToString("yyyyMMdd");
                    info.UserState = 1;
                    info.IsDel = 0;
                   info.AddTime = DateTime.Now;
                    var res = UserInforepository.Add(info);
                    //提交事务
                    scope.Complete();
                    return res;
                }
                catch (Exception ex)
                {

                    throw;
                }
              
                
            }
           


        }
       



        /// <summary>
        /// 反填用户基本信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task< PersonnelOutput> GetPersonnelByUserId(int userId)
        {
            var personnel = Personnelrepository.GetAll().FirstOrDefault(c => c.UserId == userId) ;
            var personneldto = mapper.Map<PersonnelOutput>(personnel);
            if (personnel != null)
            {
                return personneldto;
            }
            return null;
        }




		/// <summary>
		/// 增加人员基础信息-已存在信息走修改
		/// </summary>
		/// <param name="personnel"></param>
		/// <returns></returns>
		public async Task<int> AddPersonnel(Personnel personnel)
        {
           var personnelinfo= Personnelrepository.GetAll().AsNoTracking().FirstOrDefault
                (c=>c.PersonnelId == personnel.PersonnelId);
		
			
			if (personnelinfo == null)
            {
			

				return Personnelrepository.Add(personnel);

			}

			//如果存在，则更新
            //不追踪


         
			 
                    
			return Personnelrepository.Update(personnel);

		 






		}


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task< UserInfoOutput> UserLogin( string name,string pwd)
        {
            
            var userInfo =  UserInforepository.GetAll().FirstOrDefault(c => c.UserName == name && c.UserPassWord == pwd);
            var userdto=   mapper.Map<UserInfoOutput>(userInfo);

            return     userdto;
        }

		//根据用户ID反填显示个人信息  GetUserInfoById
		public async Task<object> GetUserInfoById(int userId)
        {
            var userInfo = UserInforepository.GetAll().Where(c => c.UserId == userId && c.IsDel == 0).ToList();
            var personnel = Personnelrepository.GetAll().Where(c => c.UserId==userId).ToList();
            if (personnel.Count == 0)
            {
                return userInfo.FirstOrDefault();

			}


            var userperinfo = (
                  from userinfo in userInfo
                  join person in personnel
                  on userinfo.UserId equals person.UserId
                  select new
                  {
                      userinfo.UserId,
                      userinfo.UserName,
                      userinfo.HeadImage,
                      userinfo.UserNikeName,
                      userinfo.UserSex  ,
                      userinfo.UserTrueName,
                      userinfo.UserIdType,
                      userinfo.UserPhone,
                      userinfo.UserIdCard,
                      userinfo.UserEmail,

                      userinfo.UserCode,
                      userinfo.StaffState,
                   
                    userinfo.DateOnBoard,
                    userinfo.PositiveDates,
                    //单位
                      userinfo.DepartmentId,
                      userinfo.Position,
                      userinfo.PostStation,
                      userinfo.PersonnelLevel,
                      userinfo.   BusinessId,
                     

                      person.PersonnelInPlace,



                     
                  }



                ).FirstOrDefault();



            return   userperinfo;
        }
       /// <summary>
       /// 根据用户id修改用户头像
       /// </summary>
       /// <param name="userId"></param>
       /// <param name="headImage"></param>
       /// <returns></returns>
        public async Task<int> UpdateUserHeadImage(int userId, string headImage)
        {
            var userinfo = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == userId);
            if (userinfo != null)
            {
                userinfo.HeadImage = headImage;
                return UserInforepository.Update(userinfo);

			}

            return -1; //修改失败
        }


        //根据用户id反填员工基本信息todo
        public async Task<UserInfoOutput> GetbaseUserInfoById(int userId)
        {
            var userInfo = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == userId && c.IsDel == 0) ;
            var userdto= mapper.Map<UserInfoOutput>(userInfo);
            if (userInfo != null)
            {
                return userdto;

            }
            return null;
        }



        /// <summary>
        /// 根据用户id修改用户名称
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task< int> UpdateUserName(UserInfoUpdateInput input)
        {
            var userinfo = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == input.UserId);
            if (userinfo != null)
            {
                userinfo.UserName = input.UserName;
                return UserInforepository.Update(userinfo);
            }
           return -1; //修改失败
        
        }


        /// <summary>
        /// 根据用户id修改用户密码    
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<int> UpdateUserPwd(UserInfoUpdatePwdInput input)
        {
            var userinfo = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == input.UserId);
            if (userinfo != null)
            {
                userinfo.UserPassWord = input.UserPassWord;
                return UserInforepository.Update(userinfo);
            }
            return -1; //修改失败

        }

      
        /// <summary>
        /// 根据用户id修改任职信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> UpdateStaffInfo(UpdateStaffInput input)
        {
            var userinfo = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == input.UserId);
            if (userinfo != null)
            {
                userinfo.StaffState = input.StaffState;
                userinfo.DateOnBoard = input.DateOnBoard;
                userinfo.PositiveDates = input.PositiveDates;
                userinfo.UserCode = input.UserCode;

                
                return UserInforepository.Update(userinfo);
            }
            return -1; //修改失败
        }



        /// <summary>
        /// 逻辑删除用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<int> UserInfoDelete(int userId)
        {
            var userinfoentity= UserInforepository.GetAll().FirstOrDefault(c => c.UserId == userId && c.IsDel==0);
            if (userinfoentity != null)
            {
                userinfoentity.IsDel=1;
                return    UserInforepository.Update(userinfoentity);
            }
            return   -1; //删除失败
        }


        /// <summary>
        /// 冻结解冻账号   启用状态---1 启用 0 禁用 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public async Task<int> UpdateUserState(int userId,int userState)
        {
            var userinfoentity = UserInforepository.GetAll().FirstOrDefault(c => c.UserId == userId && c.IsDel == 0);
            if (userinfoentity != null)
            {
                userinfoentity.UserState = userState;
                return UserInforepository.Update(userinfoentity);
            }
            return -1; //修改失败
        }
    }
}
